package com.company.aicrawlers.controller.api;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.company.aicrawlers.common.dto.ApiResponse;
import com.company.aicrawlers.common.dto.PageResponse;
import com.company.aicrawlers.entity.CollectTask;
import com.company.aicrawlers.service.CollectTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 采集任务 API Controller
 *
 * @author AI Crawlers
 * @since 2025-10-10
 */
@Slf4j
@RestController
@RequestMapping("/api/collect-tasks")
public class CollectTaskApiController {

    @Autowired
    private CollectTaskService collectTaskService;

    /**
     * 创建采集任务
     * 
     * 接口：POST /api/collect-tasks
     *
     * @param requestBody 请求体
     * @return 任务ID
     */
    @PostMapping(value = "", name = "createTask")
    public ApiResponse<Map<String, Object>> createTask(@RequestBody Map<String, Object> requestBody) {
        String taskName = (String) requestBody.get("taskName");
        @SuppressWarnings("unchecked")
        List<String> platforms = (List<String>) requestBody.get("platforms");
        @SuppressWarnings("unchecked")
        List<Integer> questionIdInts = (List<Integer>) requestBody.get("questionIds");
        String remark = (String) requestBody.get("remark");

        // 转换questionIds为Long类型
        List<Long> questionIds = questionIdInts.stream()
            .map(Long::valueOf)
            .collect(java.util.stream.Collectors.toList());

        Long taskId = collectTaskService.createTask(taskName, platforms, questionIds, remark);

        Map<String, Object> result = new java.util.HashMap<>();
        result.put("taskId", taskId);
        result.put("totalQuestions", questionIds.size());
        result.put("totalCollects", questionIds.size() * platforms.size());

        return ApiResponse.success(result, "任务创建成功");
    }

    /**
     * 查询任务列表
     * 
     * 接口：GET /api/collect-tasks
     *
     * @param page   页码
     * @param size   每页大小
     * @param status 任务状态（可选）
     * @return 分页结果
     */
    @GetMapping(value = "", name = "getTaskList")
    public ApiResponse<PageResponse<CollectTask>> getList(
        @RequestParam(defaultValue = "1") Integer page,
        @RequestParam(defaultValue = "10") Integer size,
        @RequestParam(required = false) String status) {

        Page<CollectTask> pageParam = new Page<>(page, size);
        IPage<CollectTask> pageResult = collectTaskService.getPageList(pageParam, status);

        PageResponse<CollectTask> response = new PageResponse<>();
        response.setList(pageResult.getRecords());
        response.setTotal(pageResult.getTotal());
        response.setPage((int) pageResult.getCurrent());
        response.setSize((int) pageResult.getSize());

        return ApiResponse.success(response);
    }

    /**
     * 获取任务详情（含问句列表和执行状态）
     * 
     * 接口：GET /api/collect-tasks/{id}
     *
     * @param id 任务ID
     * @return 任务详情
     */
    @GetMapping(value = "/{id}", name = "getTaskDetail")
    public ApiResponse<Map<String, Object>> getDetail(@PathVariable("id") Long id) {
        Map<String, Object> detail = collectTaskService.getTaskDetail(id);
        return ApiResponse.success(detail);
    }

    /**
     * 获取任务的未执行问句列表（断点续传核心接口）⭐
     * 
     * 接口：GET /api/collect-tasks/{id}/pending-questions
     *
     * @param id 任务ID
     * @return 未执行的问句×平台组合
     */
    @GetMapping(value = "/{id}/pending-questions", name = "getPendingQuestions")
    public ApiResponse<Map<String, Object>> getPendingQuestions(@PathVariable("id") Long id) {
        Map<String, Object> result = collectTaskService.getPendingQuestions(id);
        return ApiResponse.success(result);
    }

    /**
     * 取消任务
     * 
     * 接口：PUT /api/collect-tasks/{id}/cancel
     *
     * @param id 任务ID
     * @return 成功信息
     */
    @PutMapping(value = "/{id}/cancel", name = "cancelTask")
    public ApiResponse<Void> cancelTask(@PathVariable("id") Long id) {
        collectTaskService.cancelTask(id);
        return ApiResponse.success("任务已取消");
    }

    /**
     * 删除任务
     * 
     * 接口：DELETE /api/collect-tasks/{id}
     *
     * @param id 任务ID
     * @return 成功信息
     */
    @DeleteMapping(value = "/{id}", name = "deleteTask")
    public ApiResponse<Void> deleteTask(@PathVariable("id") Long id) {
        collectTaskService.deleteTask(id);
        return ApiResponse.success("任务已删除");
    }
}

